package use.io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FastCopyExample {
    public static void main(String[] args) throws IOException {
        String src = "/home/x/aa";
        String dest = "/tmp/aa";
        fastCopy(src, dest);
    }
    public static void fastCopy(String src, String dest) throws IOException {
        /*获取源文件的输入字节流*/
        FileInputStream fis = new FileInputStream(src);
        /*获取输入字节流的文件通道*/
        FileChannel fcin = fis.getChannel();
        /*获取目标文件的输出字节流*/
        FileOutputStream fos = new FileOutputStream(dest);
        /*获取输出字节流的文件通道*/
        FileChannel fcout = fos.getChannel();

        /*缓冲区大小*/
        ByteBuffer bb = ByteBuffer.allocate(1024);
        while (true) {
            /*从输入通道中读取数据到缓冲区中*/
            int r = fcin.read(bb);
            /*read返回－１表示ＥＯＦ*/
            if (r == -1) {
                break;
            }
            /*切换读写*/
            bb.flip();

            /*把缓存区的内容写到输出文件中*/
            fcout.write(bb);

            /*清空缓存区*/
            bb.clear();
        }
        fis.close();
        fos.close();
        fcin.close();
        fcout.close();

    }

}
